package at.jku.novellbedsidedevice.datasource.calendar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.provider.CalendarContract.Events;
import android.util.Log;
import at.jku.novellbedsidedevice.datasource.AbstractDataSource;

public class CalendarDatasource extends AbstractDataSource<CalendarDataObject> {

	private Context context;

	public CalendarDatasource(Context context) {
		this.context = context;
	}

	@Override
	public List<CalendarDataObject> getData() {
		ArrayList<CalendarDataObject> list = new ArrayList<CalendarDataObject>();

		final String[] projection = new String[] { Events.DTSTART, Events.TITLE };

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		long yesterday = cal.getTimeInMillis();
		cal.add(Calendar.DATE, 1);
		long tomorrow = cal.getTimeInMillis();

		final String selection = Events.DTSTART + " < ? AND " + Events.DTSTART + " > ?";
		final String[] selectionArgs = new String[] { Long.toString(tomorrow), Long.toString(yesterday) };

		final String sortOrder = Events.DTSTART + " DESC";

		Cursor cursor = null;
		try {
			cursor = context.getContentResolver().query(Events.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
			while (cursor.moveToNext()) {
				Date beginDate = new Date(cursor.getLong(cursor.getColumnIndex(Events.DTSTART)));
				String title = cursor.getString(cursor.getColumnIndex(Events.TITLE));

				list.add(new CalendarDataObject(title, beginDate));
			}
		} catch (Exception ex) {
			Log.e("NBSD", "ERROR: " + ex.toString(), ex);
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
		return list;
	}
}
